package com.xyzwps.collections;

import java.util.Iterator;

public class Range implements Iterable<Integer> {

    /**
     * 上界
     */
    private final int sup;

    /**
     * 下界
     */
    private final int inf;

    private Range(int inf, int sup) {
        this.inf = inf;
        this.sup = sup;
    }

    /**
     * 创建一个下界为 0，上界为 {@code sup} 的 {@link Range}。
     *
     * @throws IllegalArgumentException 如果 {@code sup} 小于 0
     */
    public static Range create(int sup) {
        if (sup >= 0) {
            return new Range(0, sup);
        } else {
            throw new IllegalArgumentException("sup should be greater than or equal to 0");
        }
    }

    /**
     * 创建一个下界为 {@code inf} 上界为 {@code sup} 的 {@link Range}。
     *
     * @throws IllegalArgumentException 如果 {@code sup} 小于 {@code inf}
     */
    public static Range create(int inf, int sup) {
        if (sup < inf) {
            throw new IllegalArgumentException("sup cannot less than inf");
        }
        return new Range(inf, sup);
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Itr();
    }

    private class Itr implements Iterator<Integer> {

        int curr = inf - 1;

        @Override
        public boolean hasNext() {
            return curr < sup;
        }

        @Override
        public Integer next() {
            return ++curr;
        }
    }
}
